const express = require('express');
const Card = require('../models/Card'); // 导入Card模型
const Connection = require('../models/Connection'); // 导入Connection模型


const router = express.Router();
// 获取所有卡片
router.get('/', async (req, res) => {
  try {
    const { tabId } = req.query;
    const query = tabId ? { tabId } : {};
    const cards = await Card.find(query);
    res.json({ code: 0, data: cards });
  } catch (error) {
    res.status(500).json({ code: -1, message: '服务器错误', error: error.message });
  }
});

// 创建新卡片
router.post('/', async (req, res) => {
  try {
    const { title, content, color, x, y, width, height, tabId } = req.body;

    if (!title || !content || !tabId) {
      return res.status(400).json({ code: -1, message: '标题、内容和标签ID是必需的' });
    }

    const newCard = new Card({
      id: Date.now().toString(), // 使用时间戳作为唯一ID
      title,
      content,
      color: color || '#ffffff',
      x: x || 0,
      y: y || 0,
      width: width || 200,
      height: height || 150,
      tabId,
    });

    await newCard.save();
    res.status(201).json({ code: 0, data: newCard });
  } catch (error) {
    res.status(400).json({ code: -1, message: '创建卡片失败', error: error.message });
  }
});

// 更新卡片
router.put('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const { title, content, color, x, y, width, height, tabId } = req.body;

    const card = await Card.findOne({ id });

    if (!card) {
      return res.status(404).json({ code: -1, message: '找不到卡片' });
    }

    // 更新卡片信息
    if (title !== undefined) card.title = title;
    if (content !== undefined) card.content = content;
    if (color !== undefined) card.color = color;
    if (x !== undefined) card.x = x;
    if (y !== undefined) card.y = y;
    if (width !== undefined) card.width = width;
    if (height !== undefined) card.height = height;
    if (tabId !== undefined) card.tabId = tabId;

    await card.save();
    res.json({ code: 0, data: card });
  } catch (error) {
    res.status(400).json({ code: -1, message: '更新卡片失败', error: error.message });
  }
});

// 删除卡片
router.delete('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    // 先删除与该卡片相关的所有连接
    await Connection.deleteMany({ $or: [{ from: id }, { to: id }] })
    await Card.findOneAndDelete({ id })

    res.json({ code: 0, message: '卡片和相关连接删除成功' });
  } catch (error) {
    res.status(500).json({ code: -1, message: '删除卡片失败', error: error.message });
  }
});

module.exports = router;